import { Service } from 'egg';

export default class AdminLoginService extends Service {
    public async login(username: string, password: string) {
        const { ctx, service } = this;
        const user = await service.db.user.findOneByPassword(username, password);
        if (!user) {
            ctx.helper.unauth();
        }
        return {
            ...user,
            token: this.generateJwt(user!.id),
        };
    }

    private generateJwt(userId: number) {
        const jwtSecret = this.ctx.app.config.jwt.secret;
        const token = this.ctx.app.jwt.sign({
            userId,
        }, jwtSecret, {
            expiresIn: '30d',
        });
        return token;
    }
}
